<?php

/**
 * 文件注释
 *
 * Author: Liam
 * Datetime: 03/29/18 00:00 PM
 */

namespace ApiBundle\Controller;

use BaseBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

class PublicController extends BaseController
{
    /**
     * 上传图片
     *
     * @return JsonResponse
     */
    public function uploadImageAction(Request $request)
    {
        if (isset($_FILES['image']) && $_FILES['image']['name']) {
            $date = date('Ym');
            $path = $this->getParameter('dir_upload') . DIRECTORY_SEPARATOR . $date . DIRECTORY_SEPARATOR;
            $data = $this->uploadImage('image', $path, uniqid());

            if (isset($data['path'])) {
                $result = array('errorCode' => 0, 'message' => '上传成功', 'data' => array('path' => $data['path']));
            } else {
                $result = array('errorCode' => 1, 'message' => current($data['errors']));
            }
        } else {
            $result = array('errorCode' => 2, 'message' => '请上传图片');
        }

        return new JsonResponse($result);
    }

    /**
     * 设置图形验证码
     *
     * @return JsonResponse
     */
    public function verificationCodeAction(Request $request)
    {
        $image = imagecreatetruecolor(100, 40);

        $verifyCode = '';
        for($i = 0; $i < 4; $i++) {
            $verifyCode .= rand(0, 9);
        }

        //  设置session
        $this->get('session')->set('verify_code', $verifyCode);

        //白色背景
        $white = imagecolorallocate($image, 255, 255, 255);
        //字体颜色
        $fontStyle = imagecolorallocate($image, rand(0, 255),rand(0, 255), rand(0, 255));;
        imagefill($image, 0, 0, $white);
        imagestring($image, 5, 10, 10, $verifyCode, $fontStyle);
        //加入干扰点
        for($i = 0; $i < 80; $i++) {
            $color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imagesetpixel($image, rand(0, 100), rand(0,40), $color);
        }
        //干扰线
        for($i = 0; $i < 5; $i++) {
            $color = imagecolorallocate($image, rand(0, 255), rand(0, 255), rand(0, 255));
            imageline($image, rand(0, 100), rand(0, 40), rand(0, 100), rand(0, 40), $color);
        }
        //输出图片
        header("Content-type: image/png");
        imagepng($image);
        //释放资源
        imagedestroy($image);

        return new JsonResponse('生成成功', $image);
    }
}